import { Loader } from "@googlemaps/js-api-loader";
import { useRef, useEffect } from "react";
import "./App.css";

function App() {
  const mapContainerRef = useRef(null);
  const mapRef = useRef(null);
  const routePolylineRef = useRef(null);
  const markersRef = useRef([]);
  const animationIntervalRef = useRef(null);

  // 添加标记
  const addMarkers = async (coordinates) => {
    const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");

    // 清除旧标记
    markersRef.current.forEach((marker) => marker.setMap(null));
    markersRef.current = [];

    coordinates.forEach((coord, index) => {
      const position = { lat: coord[1], lng: coord[0] };
      const marker = new AdvancedMarkerElement({
        map: mapRef.current,
        position: position,
        title: index === 0 ? "Start" : index.toString(),
      });

      // 添加信息窗口
      const infoWindow = new google.maps.InfoWindow({
        content: `<h3>${index === 0 ? "Start" : index}</h3>`,
      });

      marker.addListener("click", () => {
        infoWindow.open(mapRef.current, marker);
      });

      markersRef.current.push(marker);
    });
  };

  // 绘制路线
  const drawRoute = (path) => {
    if (routePolylineRef.current) {
      routePolylineRef.current.setMap(null);
    }

    routePolylineRef.current = new google.maps.Polyline({
      path,
      geodesic: true,
      strokeColor: "#3b8ddd",
      strokeOpacity: 1.0,
      strokeWeight: 5,
      map: mapRef.current,
    });
  };

  // 实时绘制路线
  const animateDrawRoute = (path) => {
    let currentStep = 0;
    animationIntervalRef.current = setInterval(() => {
      if (currentStep > path.length) {
        clearInterval(animationIntervalRef.current);
        return;
      }
      const newPath = path.slice(0, currentStep + 1);
      routePolylineRef.current.setPath(newPath);
      currentStep++;
    }, 1500);
  };

  // 获取路线数据函数
  const getRoute = (coordinates) => {
    return new Promise((resolve, reject) => {
      const directionsService = new google.maps.DirectionsService();
      const origin = new google.maps.LatLng(
        coordinates[0][1],
        coordinates[0][0]
      );
      const destination = new google.maps.LatLng(
        coordinates[1][1],
        coordinates[1][0]
      );

      directionsService.route(
        {
          origin,
          destination,
          travelMode: google.maps.TravelMode.DRIVING,
        },
        (response, status) => {
          if (status === "OK") {
            const path = response.routes[0].overview_path;
            resolve(path);
          } else {
            reject(new Error("Directions request failed: " + status));
          }
        }
      );
    });
  };

  useEffect(() => {
    const loader = new Loader({
      apiKey: "AIzaSyCCkUuNmo5r0uKu17g6CCh0_DuDu8iB7_g",
      version: "weekly",
    });

    loader.importLibrary("core").then(async () => {
      const { Map } = await google.maps.importLibrary("maps");
      // 初始化地图
      mapRef.current = new Map(mapContainerRef.current, {
        center: { lat: 37.78, lng: -122.42 },
        zoom: 12,
        mapId: "DEMO_MAP_ID",
      });

      // 坐标点数据
      const coordinates = [
        [-122.42, 37.78], // 起点
        [-122.49, 37.85], // 终点
      ];

      // 添加标记
      addMarkers(coordinates);

      // 直接绘制规划路线
      const path = await getRoute(coordinates);
      drawRoute(path);

      setTimeout(() => {
        alert("实时绘制规划路线");
        animateDrawRoute(path);
      }, 3000);
    });

    // 清理函数
    return () => {
      if (animationIntervalRef.current)
        clearInterval(animationIntervalRef.current);
      markersRef.current.forEach((marker) => marker.setMap(null));
      if (routePolylineRef.current) routePolylineRef.current.setMap(null);
      if (mapRef.current) mapRef.current = null;
    };
  }, []);

  return <div id="map-container" ref={mapContainerRef} />;
}

export default App;
